package com.emmy.walnut.view;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.emmy.walnut.BuildConfig;
import com.emmy.walnut.R;
import com.emmy.walnut.constant.AppConstant;
import com.emmy.walnut.presenter.ExportPresenter;
import com.emmy.walnut.presenter.iface.ExportPIface;
import com.emmy.walnut.util.TimeStampUtil;
import com.emmy.walnut.view.iface.ExportIface;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.io.File;
import java.util.Calendar;

public class ExportActivity extends BaseActivity implements ExportIface {

    private EditText editText;
    private EditText startTimeText;
    private EditText endTimeText;
    private Button createButton;
    private RadioGroup radioGroup;

    private int[] selectedItems;
    private long startTime;
    private long endTime;


    private Calendar calendar;
    private int year;
    private int month;
    private int day;

    private ExportPIface exportPIface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_export);
        exportPIface = new ExportPresenter(this);
        init();
    }

    private void init(){

        calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH);
        day = calendar.get(Calendar.DAY_OF_MONTH);

        radioGroup = findViewById(R.id.orderGroup);

        editText = findViewById(R.id.labelEditText);
        editText.setKeyListener(null);
        editText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final CharSequence[] items = new CharSequence[AppConstant.activities.size()];
                selectedItems = new int[AppConstant.activities.size()];
                for (int i = 0; i< AppConstant.activities.size(); i++){
                    items[i] = AppConstant.activities.get(i).getLabelName();
                    selectedItems[i] = i;
                }
                final QMUIDialog.MultiCheckableDialogBuilder multiCheckableDialogBuilder =
                        new QMUIDialog.MultiCheckableDialogBuilder(ExportActivity.this)
                        .addItems(items, null).setCheckedItems(selectedItems)
                        .addAction("取消", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                dialog.dismiss();
                            }
                        });
                multiCheckableDialogBuilder.addAction("确认", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        selectedItems = multiCheckableDialogBuilder.getCheckedItemIndexes();
                        editText.setText("已选"+items.length+"个类别");
                        dialog.dismiss();
                    }
                });
                multiCheckableDialogBuilder.show();
            }
        });

        startTimeText = findViewById(R.id.startTimeEditText);
        startTimeText.setKeyListener(null);
        startTimeText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerDialog datePickerDialog = new DatePickerDialog(ExportActivity.this,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                                StringBuilder stringBuilder = new StringBuilder();
                                stringBuilder.append(year);
                                stringBuilder.append("年");
                                stringBuilder.append(month+1);
                                stringBuilder.append("月");
                                stringBuilder.append(dayOfMonth);
                                stringBuilder.append("日");
                                calendar.set(Calendar.YEAR, year);
                                calendar.set(Calendar.MONTH, month);
                                calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                                startTime = TimeStampUtil.getDailyStartTime(calendar.getTimeInMillis());
                                startTimeText.setText(stringBuilder.toString());
                            }
                        }, year, month, day);
                datePickerDialog.show();
            }
        });

        endTimeText = findViewById(R.id.endTimeEditText);
        endTimeText.setKeyListener(null);
        endTimeText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerDialog datePickerDialog = new DatePickerDialog(ExportActivity.this,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                                StringBuffer stringBuffer = new StringBuffer();
                                stringBuffer.append(year);
                                stringBuffer.append("年");
                                stringBuffer.append(month+1);
                                stringBuffer.append("月");
                                stringBuffer.append(dayOfMonth);
                                stringBuffer.append("日");
                                calendar.set(Calendar.YEAR, year);
                                calendar.set(Calendar.MONTH, month);
                                calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                                endTime = TimeStampUtil.getDailyEndTime(calendar.getTimeInMillis());
                                endTimeText.setText(stringBuffer.toString());
                            }
                        }, year, month, day);
                datePickerDialog.show();
            }
        });

        createButton = findViewById(R.id.create);
        createButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (editText.getText().toString().equals("")){
                    Toast.makeText(ExportActivity.this, "请选择需要导出的类别",
                            Toast.LENGTH_SHORT).show();
                    return;
                }else if (startTimeText.getText().toString().equals("")){
                    Toast.makeText(ExportActivity.this, "请选择需要导出的开始时间",
                            Toast.LENGTH_SHORT).show();
                    return;
                }else if (endTimeText.getText().toString().equals("")){
                    Toast.makeText(ExportActivity.this, "请选择需要导出的结束时间",
                            Toast.LENGTH_SHORT).show();
                    return;
                }else if (startTime>=endTime){
                    Toast.makeText(ExportActivity.this, "开始时间需要早于结束时间",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                exportPIface.exportData(selectedItems, startTime, endTime,
                        (radioGroup.getCheckedRadioButtonId()== R.id.orderByLabel));
            }
        });
    }

    @Override
    public void exportFile(String fileName) {

        File file = new File(getFilesDir().getAbsolutePath() + "/report",fileName);

        Intent intent = new Intent(Intent.ACTION_VIEW);
        //设置外部应用临时权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Uri fileUri = null;
        if(Build.VERSION.SDK_INT>=24){
            fileUri = FileProvider.getUriForFile(this,
                    BuildConfig.APPLICATION_ID+".fileProvider",
                    file);
        }else{
            fileUri = Uri.fromFile(file);
        }
        intent.setData(fileUri);
        intent.putExtra(Intent.EXTRA_STREAM, fileUri);
        startActivity(intent);
    }
}
